<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;


class Dish extends Base
{

    public function __construct()
    {

    }

    const ROOM_DISH_AWARD = 'ROOM:DISH:AWARD';//房间内开奖
    const PAY_DISH_LIST = 'PAY:DISH:LIST';//付费打碟房间
    const PAY_DISH_ROOM_ID = 'PAY:DISH:ROOM:ID';//付费打碟房间id合集
    const PAY_DISH_ROOM_TO_USER = 'PAY:DISH:ROOM:TO:USER';//付费打碟参与用户
    const PAY_AWARD_POND_USER_ID = 'PAY:AWARD:POND:USER';//付费奖池id
    const PAY_AWARD_GIFT_ID_LOG = 'PAY:AWARD:GIFT:ID';//付费获得奖品记录id
    const DISH_GIFT_DIAMOND_SUM = 'DISH:GET:GIFT:DIAMOND:SUM';//支出礼物钻石数量
    const DISH_MALL_DIAMOND_SUM = 'DISH:GET:MALL:DIAMOND:SUM';//支出座驾数量
    const DISH_OPEN_DIAMOND_SUM = 'DISH:PAY:DIAMOND:SUM';//用户开启支付钻石数量
    const DISH_PAY_DIAMOND_SUM = 'DISH:PAY:DIAMOND:SUM';//用户参与支付钻石数量

    const FREE_DISH_LIST = 'FREE:DISH:DATE';//免费打碟房间时间
    const FREE_DISH_CLICK_TIME = 'FREE:DISH:CLICK:DATE';//免费打碟可点击时间
    const FREE_DISH_ROOM_ID = 'FREE:DISH:ROOM:ID';//免费打碟房间id合集
    const FREE_DISH_ROOM_TO_USER = 'FREE:DISH:ROOM:TO:USER';//免费打碟参与用户
    const AWARD_POND_ALL = 'AWARD:POND:COUNT';//奖池数量统计
    const FREE_AWARD_POND_USER_ID = 'FREE:AWARD:POND:USER';//免费奖池用户id
    const FREE_AWARD_GIFT_ID_LOG = 'FREE:AWARD:GIFT:ID:LOG';//免费获得奖品记录id
    const FREE_IS_AWARD = 'FREE:AWARD:STATUS';//是否发放奖励
    const FREE_ALL_AWARD_NUM = 'FREE:ALL:AWARD:NUM';//发放奖励次数

    const award_gift_probability_0 = [0.0004, 0.0010, 0.0010, 0.0010, 0.0050, 0.0050, 0.01, 0.0010, 0.0010, 0.0010, 0.0010, 0.9726];//1级奖池概率
    const award_gift_probability_1 = [0.0004, 0.0004, 0.0016, 0.0030, 0.0050, 0.0080, 0.0080, 0.0020, 0.0050, 0.0100, 0.0100, 0.9466];//2级奖池概率
    const award_gift_probability_2 = [0.0001, 0.0010, 0.0025, 0.0050, 0.0060, 0.0100, 0.7904, 0.0020, 0.0030, 0.0300, 0.1500];//3级奖池概率
    const award_gift_id_0 = [188, 88, 38, 10, 1, 231, 200, 199];//0级奖池礼物
    const award_gift_id_1 = [327, 326, 128, 169, 328, 329, 330, 188, 88, 38, 10, 1];//1级奖池礼物
    const award_gift_id_2 = [327, 326, 128, 169, 328, 329, 330, 188, 88, 38, 10, 2];//2级奖池礼物
    const award_gift_id_3 = [331, 327, 326, 128, 169, 328, 329, 188, 88, 10, 5];//3级奖池礼物
    const mall_list = [231, 200, 199];//座驾id


    /*
     * 付费打碟
     * @param $room_id 房间id
     * @param $minute 持续时间
     * @param $level 奖励等级
     * */
    public function addPayDishCache($room_id, $time, $level = 1)
    {
        $key = self::PAY_DISH_LIST . '-' . $room_id;
        return Redis::HSET($key, $room_id, $level);
    }


    //生成付费打碟房间id合集
    public function createPayRoomIdCache($room_id, $time)
    {
        $key = self::PAY_DISH_ROOM_ID;
        $timeout = time() + $time;
        return Redis::ZADD($key, $timeout, $room_id);
    }


    public function getPayRoomId($room_id)
    {
        $key = self::PAY_DISH_ROOM_ID;
        return Redis::ZSCORE($key, $room_id);
    }

    //获取可以开奖的所有付费房间id合集
    public function getPayRoomIdCache($time = '')
    {
        if (empty($time)) {
            $time = time();
        }
        $key = self::PAY_DISH_ROOM_ID;
        return Redis::ZRANGEBYSCORE($key, 0, $time, 'WITHSCORES');
    }

    //删除待开奖池子id
    public function delPayRoomIdCache($room_id)
    {
        $key = self::PAY_DISH_ROOM_ID;
        return Redis::ZREM($key, $room_id);
    }

    //获取房间是否付费打碟
    public function getPayDishCache($room_id)
    {
        $key = self::PAY_DISH_ROOM_ID;
        return Redis::ZSCORE($key, $room_id);
    }

    /*
     * 开启免费打碟
     *
     * */
    public function startFreeDish()
    {
        $k = 'freeTime';
        $key = self::FREE_DISH_LIST;
        Redis::HSET($key, $k, time());
        $timeout = 7 * 60;
        $ttl = Redis::TTL($key);
        if ($ttl == -1) {
            Redis::EXPIRE($key, $timeout);
        }
        return true;
    }

    //修改免费打碟发放奖励时间
    public function updateFreeDishAwardTime($time = 60)
    {
        $k = 'freeTime';
        $key = self::FREE_DISH_LIST;
        return Redis::HSET($key, $k, $time);
    }

    //生成免费打碟房间id合集
    public function createFreeRoomIdCache($room_id)
    {
        $key = self::FREE_DISH_ROOM_ID;
        Redis::HSET($key, $room_id, 0);//次数为0
        $timeout = 7 * 60;
        $ttl = Redis::TTL($key);
        if ($ttl == -1) {
            Redis::EXPIRE($key, $timeout);
        }
        return true;
    }

    //修改免费打碟房间发放奖品次数

    public function updateFreeRoomAwardNum($room_id)
    {
        $key = self::FREE_DISH_ROOM_ID;
        Redis::HINCRBY($key, $room_id, 1);//次数+1
        return true;
    }


    //获取所有免费房间id合集
    public function getFreeRoomIdCache($room_id = '')
    {
        $key = self::FREE_DISH_ROOM_ID;
        if ($room_id) {
            return Redis::HGET($key, $room_id);
        }
        return Redis::HGETALL($key);
    }


    /*
     * 查看是否开启免费打碟
     *
     * */
    public function getFreeDish()
    {
        $k = 'freeTime';
        $key = self::FREE_DISH_LIST;
        return Redis::HGET($key, $k);
    }


    /*
     * 查看是否开启付费打碟
     * */
    public function getPayDish($room_id)
    {
        $key = self::PAY_DISH_LIST . '-' . $room_id;
        return Redis::HGETALL($key);
    }

    /*
     * 删除付费打碟等级
     * */
    public function delPayDishLevel($room_id)
    {
        $key = self::PAY_DISH_LIST . '-' . $room_id;
        return Redis::DEL($key);
    }

    /*
     * 用户参与付费房间打碟
     * 多次点击 + 1
     *
     * */
    public function addPayDishRoomToUser($room_id, $user_id)
    {
        $key = self::PAY_DISH_ROOM_TO_USER . '-' . $room_id;
        return Redis::HINCRBY($key, $user_id, '1');
    }

    //获取房间付费打碟参与用户id
    public function getPayDishUserId($room_id, $user_id = '')
    {
        $key = self::PAY_DISH_ROOM_TO_USER . '-' . $room_id;
        if ($user_id) {
            return Redis::HGET($key, $user_id);
        }
        return Redis::HGETALL($key);
    }

    //删除用户参与付费房间
    public function delPayDishRoomToUser($room_id, $user_id)
    {
        $key = self::PAY_DISH_ROOM_TO_USER . '-' . $room_id;
        return Redis::HDEL($key, $user_id);
    }


    /*
     * 用户参与免费房间打碟
     *
     * */
    public function addFreeDishRoomToUser($room_id, $user_id)
    {
        $key = self::FREE_DISH_ROOM_TO_USER . '-' . $room_id;
        Redis::HSET($key, $user_id, 1);
        $timeout = 60 * 7;
        $ttl = Redis::TTL($key);
        if ($ttl == -1) {
            Redis::EXPIRE($key, $timeout);
        }
        return true;
    }

    /*
     * 查看房间免费打碟参与用户
     * */
    public function getFreeDishALLUserToRoom($room_id)
    {
        $key = self::FREE_DISH_ROOM_TO_USER . '-' . $room_id;
        return Redis::HGETALL($key);
    }

    //删除房间参与用户记录
    public function delFreeDishUser($room_id, $user_id)
    {
        //
        $key = self::FREE_DISH_ROOM_TO_USER . '-' . $room_id;
        return Redis::HDEL($key, $user_id);

    }

    /*
     * 查看用户是否参与免费打碟
     *
     * */
    public function getFreeDishUserToRoom($room_id, $user_id)
    {
        $key = self::FREE_DISH_ROOM_TO_USER . '-' . $room_id;
        return Redis::HGET($key, $user_id);
    }

    /*
     * 房间内开奖入延迟队列
     * @param $room_id  房间id
     * @param $user_id  开奖用户id
     * @param $level  奖品等级
     * @param $minute  延迟时间
     * */
    public function roomDishAwardAdd($room_id, $user_id, $level, $minute)
    {
        $key = self::ROOM_DISH_AWARD;
        $value = $room_id . '/' . $user_id . '/' . $level;
        $time = time() + $minute * 60;// 延时时间
        $res = true;
        do {
            try {
                //加入房间奖励缓存
                Redis::ZADD($key, 'NX', $time, $value);
                return $res;
            } catch (\Exception $e) {
                // 记录日志， 添加监控 ，异步根据监控内容处理。
                write_log('addRoomDishAwardError', 'addError', $key . '-' . $value);//插入房间开奖缓存失败
            }
            return false;
        } while (false);
    }

    //创建打碟奖池
    public function createAwardPond($level = 0)
    {
        //查询奖池总数量
        $key = self::AWARD_POND_ALL . '-' . $level;
        $sum_num = Redis::LLEN($key);
        if ($sum_num > 0) {
            return false;
        }
        switch ($level) {
            case 1:
                $gift_ids = self::award_gift_id_1;
                $num = [1, 3, 3, 10, 50, 50, 5100, 3, 10, 10, 10, 4750];
                break;
            case 2:
                $gift_ids = self::award_gift_id_2;
                $num = [1, 2, 10, 20, 20, 1000, 3000, 2, 20, 100, 100, 5725];
                break;
            case 3:
                $gift_ids = self::award_gift_id_3;
                $num = [1, 10, 25, 50, 60, 100, 7905, 20, 30, 300, 1499];
                break;
            default:
                $num = [1, 3, 10, 65, 3500, 1230, 2900, 2291];
                $gift_ids = self::award_gift_id_0;
                break;
        }
        $pond_arr = [];
        foreach ($num as $k => $v) {
            $arr = array_fill(0, $v, $gift_ids[$k]);
            $pond_arr = array_merge($pond_arr, $arr);
        }
        shuffle($pond_arr);
        return Redis::LPUSH($key, $pond_arr);
    }

    /*
     * 将用户加入付费发放奖励池子
     * @param $user_id 发放用户id
     * @param $len 用户参与次数
     * @param $level 参与等级
     * */
    public function pushPayAwardPondToUser($user_id, $len, $room_id)
    {
        $key = self::PAY_AWARD_POND_USER_ID . '-' . $room_id;
        while ($len > 0) {
            Redis::LPUSH($key, $user_id);
            $len--;
        }
        return true;
    }

    //用户付费打碟池子出列
    public function popPayAwardPondToUser($room_id, $count, $level = 0)
    {
        $key = self::PAY_AWARD_POND_USER_ID . '-' . $room_id;
        $len = $length = Redis::LLEN($key);
        $msg_arr = [];
        while ($len > 0) {
            $val = Redis::LPOP($key);
            $this->awardGift($val, $level, $count, 1, $room_id);
            $len--;
            $msg_arr[$val] = $room_id;
        }
        $room_model = new  Room();
        $audio_api = new  AudioApi();
        foreach ($msg_arr as $k => $v) {
            $room_cache = $room_model->getRoomInfoToRoomIdCache($v);
            $room_cache = json_decode($room_cache, true);
            //发送消息
            $msg = '您在房间' . $room_cache['room_uid'] . '参与的打碟活动获得礼物已到账，请立即查收哟~';
            $audio_api->sendMsgApi($k, $msg);
        }
    }


    //将用户加入免费发放奖励池子
    public function pushFreeAwardPondToUser($user_id, $room_id)
    {
        $key = self::FREE_AWARD_POND_USER_ID . '-' . $room_id;
        return Redis::LPUSH($key, $user_id);
    }

    //用户免费打碟池子出列
    public function popFreeAwardPondToUser($room_id, $count, $level = 0)
    {
        $key = self::FREE_AWARD_POND_USER_ID . '-' . $room_id;//当前房间用户参与池子
        $len = Redis::LLEN($key);
        $msg_arr = [];
        while ($len > 0) {
            $user_id = Redis::LPOP($key);
            $this->awardGift($user_id, $level, $count, 0, $room_id);
            $msg_arr[$user_id] = $room_id;
            $len--;
        }
        $room_model = new  Room();
        $audio_api = new  AudioApi();
        foreach ($msg_arr as $k => $v) {
            $room_cache = $room_model->getRoomInfoToRoomIdCache($v);
            $room_cache = json_decode($room_cache, true);
            //发送消息
            $msg = '您在房间' . $room_cache['room_uid'] . '参与的打碟活动获得礼物已到账，请立即查收哟~';
            $audio_api->sendMsgApi($k, $msg);
        }
    }


    /*
     * 发放礼物
     * @$user_id 用户id
     * @$level 等级
     * @$len 参与人数  等级 1 2 小于10人 只有最低的奖品且不走奖池
     * @$type 0免费 1付费 免费的奖品且不走奖池
     * */
    public function awardGift($user_id, $level = 0, $len = 9, $type = 0, $room_id)
    {

        //查询奖池剩余数量缓存
        $key = self::AWARD_POND_ALL . '-' . $level;
        switch ($type) {
            case 0://免费
                if ($len > 9) {//爆机
                    //奖池体系
                    $gift_id = Redis::LPOP($key);
                    if ($gift_id == null) {
                        $this->createAwardPond($level);
                        $gift_id = Redis::LPOP($key);
                    }
                } else {//未爆机
                    //最便宜奖品 且不走奖池体系
                    $gift_id = 200;
                }
                break;
            default: // 付费
                if ($len > 9) {//爆机
                    //奖池体系
                    $gift_id = Redis::LPOP($key);
                    if ($gift_id == null) {
                        $this->createAwardPond($level);
                        $gift_id = Redis::LPOP($key);
                    }
                } else { //未爆机
                    $send_gift_arr = [200, 1, 330, 329];//最便宜礼物 200=>座驾  1=>1个音浪 330=>加油鸭  329=>可爱呀
                    $gift_id = $send_gift_arr[$level];
                }
                break;
        }
        //音浪
        $send_type = 1;//1礼物  2座驾
        $award_gift_num = 1;//赠送数量
        $send_all_msg = 0;//是否发送飘屏
        if (in_array($gift_id, [331, 327])) {
            //大礼物
            $send_all_msg = 1;
        }
        if (in_array($gift_id, [188, 88, 38, 10, 1, 2, 5])) {
            //音浪
            $award_gift_num = $gift_id;
            $gift_id = 332;
        }
        if (in_array($gift_id, self::mall_list)) {
            //座驾
            $send_type = 2;
        }

        $audio_api = new  AudioApi();
        //赠送道具
        $gift = new Gift();
        $type_name = '道具背包';
        if ($send_type == 1) {
            //礼物
            $audio_api->sendGift($user_id, $gift_id, 15, $award_gift_num);
            $this->userGetGiftNum(0, $gift_id, $award_gift_num);
            $gift_info = json_decode($gift->getGiftInfoCache($gift_id), true);
            $gift_name = $gift_info['name'] . '*' . $award_gift_num;
        } else {
            //座驾
            $type_name = '装扮';
            $audio_api->sendUsedMall($user_id, $gift_id, 2, $award_gift_num);
            $this->userGetGiftNum(1, $gift_id, $award_gift_num);
            $gift_info = json_decode($gift->getMallInfoCache($gift_id), true);
            $gift_name = $gift_info['goods_name'] . '*' . $award_gift_num;
        }
        $this->addAwardLog($user_id, $gift_id, $award_gift_num);

        if ($send_all_msg == 1) {
            //用户信息
            $user = new User();
            $user_info = $user->getUserInfoByApi($user_id);
            //全服飘屏
            $msg = '恭喜' . $user_info['nickname'] . '开出' . $gift_name . '——我也想要；';
            $audio_api->sendAllAppApi($user_id, $room_id, $msg);
        }
//        //发送消息
//        $msg = '您在房间' . $room_cache['room_uid'] . '参与的打碟活动获得礼物' . $gift_name . '已到您的' . $type_name . '，请立即查看哟~';
//        $audio_api->sendMsgApi($user_id, $msg);
        write_log('freeAwardGift', '发放第' . $level . '级礼物', ['user_id' => $user_id, 'gift_id' => $gift_id]);//开启房间
    }


    //删除免费打碟相关信息
    public function delFreeDishInfo($room_id)
    {
        $room_key = self::FREE_DISH_ROOM_ID;
        Redis::HDEL($room_key, $room_id);
        $user_key = self::FREE_DISH_ROOM_TO_USER . '-' . $room_id;
        Redis::DEL($user_key);
        return true;
    }


    /*
     * 获得奖励记录
     * @param $user_id 参与用户id
     * @param $level 参与等级
     * @param $gift_id 礼物id
     * */
    public function addAwardLog($user_id, $gift_id, $send_num = 1)
    {
        $num = time() . rand(0, 99999);
        $key = self::FREE_AWARD_GIFT_ID_LOG . '-' . $user_id;
        $k_v = $gift_id . '/' . date('m', time()) . '月' . date('d', time()) . '日' . '/' . $num;
        return Redis::HSET($key, $k_v, $send_num);
    }

    public function getAwardLog($user_id)
    {
        $key = self::FREE_AWARD_GIFT_ID_LOG . '-' . $user_id;
        return Redis::HGETALL($key);
    }


    public function popAward($level, $i = 5000, $type = 0)
    {
        $key = self::AWARD_POND_ALL . '-' . $level;
        $price = 0;
        if ($type == 1) {
            //删除池子
            Redis::DEL($key);
        }
        $num_i = $i;
        while ($i > 0) {
            $send_type = 1;
            $award_gift_num = 1;
            $gift_id = Redis::LPOP($key);
            if ($gift_id == null) {
                $this->createAwardPond($level);
                continue;
            }
            if (in_array($gift_id, [188, 88, 38, 10, 1, 2, 5])) {
                //音浪
                $award_gift_num = $gift_id;
                $gift_id = 332;
            }
            if (in_array($gift_id, self::mall_list)) {
                //座驾
                $send_type = 2;
            }
            $gift = new Gift();
            if ($send_type == 1) {
                //礼物
                $gift_info = json_decode($gift->getGiftInfoCache($gift_id), true);
                $price = $price + $gift_info['price'] * $award_gift_num;
            }
            $i--;
            if ($i == 0) {
                $this->createAwardPond($level);
            }
        }
        $pay_diamond = ['50', '150', '270', '500'];
        $pay_price = $pay_diamond[$level] * $num_i;
        echo '产出钻石:' . $price;
        echo '</br>';
        echo '用户支付:' . $pay_price;
    }


    /*
     * 用户总支付钻石
     * @param $type 0开启 1参与
     * @param $num 数量
     * @param $price 价值
     *
     * */
    public function incrPayDiamond($type, $price, $room_id = 0, $user_id = 0)
    {
        switch ($type) {
            case 0:
                $key = self::DISH_OPEN_DIAMOND_SUM . '-' . $room_id;//房间开启支付钻石数量
                Redis::Hset($key, $user_id, $price);
                break;
            default:
                $key = self::DISH_PAY_DIAMOND_SUM;//用户参与支付钻石数量
                Redis::INCRBY($key, $price);
                break;
        }
        return true;
    }

    /*
    * 用户总获取座驾礼物数量
    * @param $type 0礼物 1座驾
    * @param $gift_id 礼物id
    * @param $num 数量
    * */
    public function userGetGiftNum($type, $gift_id, $num)
    {
        switch ($type) {
            case 0:
                $key = self::DISH_GIFT_DIAMOND_SUM;//支出礼物数量
                break;
            default:
                $key = self::DISH_MALL_DIAMOND_SUM;//支出座驾数量
                break;
        }
        return Redis::HINCRBY($key, $gift_id, $num);
    }


    //休息时间
    public function setCheckClickTime($time = 80)
    {
        $key = self::FREE_DISH_CLICK_TIME;
        return Redis::SET($key, 1, 'EX', $time);
    }

    /*
     * 获取休息时间
     * -2 可点击
     * -1 没有时间
     *  >0  缓存时间
     * */
    public function getClickTime()
    {
        $key = self::FREE_DISH_CLICK_TIME;
        return Redis::TTL($key);
    }

    public function updateFreeStatus($status = 1, $ttl)
    {
        $key = self::FREE_IS_AWARD;
        return Redis::SET($key, $status, 'EX', $ttl);
    }

    public function getFreeStatus()
    {
        $key = self::FREE_IS_AWARD;
        return Redis::GET($key);
    }

    //设置发放奖励总次数
    public function setAwardAllNum()
    {
        $key = self::FREE_ALL_AWARD_NUM;
        return Redis::SET($key, 0, 'EX', 7 * 60);
    }

    public function getAwardAllNum()
    {
        $key = self::FREE_ALL_AWARD_NUM;
        return Redis::GET($key);
    }

    public function updateAwardAllNum()
    {
        $key = self::FREE_ALL_AWARD_NUM;
        return Redis::INCR($key);
    }

}
